package com.xhsj.user.sms.purchase.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.google.common.collect.Maps;
import com.xhsj.user.sms.purchase.entity.*;
import com.xhsj.user.sms.purchase.mapper.TbPurchaseOrderGoodsMapper;
import com.xhsj.user.sms.purchase.mapper.TbPurchaseSubtaskPaymentApplyMapper;
import com.xhsj.user.sms.purchase.mapper.TbPurchaseSubtaskPaymentRecordMapper;
import com.xhsj.user.sms.purchase.service.*;
import com.xhsj.user.utils.IdGen;
import com.xhsj.user.utils.Message;
import com.xhsj.user.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;


/**
 * <p>
 * 采购订单-主表 前端控制器
 * </p>
 *
 * @author suxiaolin
 * @since 2020-04-23
 */
@Slf4j
@Api(tags = "采购订单-主表")
@RestController
@RequestMapping("/purchase/tbPurchaseOrder")
public class TbPurchaseOrderController {

	@Autowired
    public TbPurchaseOrderService service;

	@Autowired
	private TbPurchaseOrderFileService tbPurchaseOrderFileService;

	@Autowired
	private TbPurchaseSubtaskOtherFileService tbPurchaseSubtaskOtherFileService;

	@Autowired
	private TbPurchaseOrderGoodsMapper tbPurchaseOrderGoodsMapper;

	@Autowired
	private TbPurchaseSubtaskPaymentApplyMapper tbPurchaseSubtaskPaymentApplyMapper;

    @Autowired
    private TbPurchaseSubtaskPaymentRecordMapper tbPurchaseOrderPaymentRecordMapper;

	@Autowired
	public TbPurchaseApplyService tbPurchaseApplyService;

    @Autowired
    public TbPurchaseSubtaskStatementService tbPurchaseSubtaskStatementService;

    @Autowired
    public TbPurchaseOrderSubtaskService tbPurchaseOrderSubtaskService;

//	@ApiOperation(value = "采购订单-主表,保存/修改", notes = "采购订单-主表,保存和修改方法")
//	@RequestMapping(value = "/save", method = RequestMethod.POST)
//    //@PreAuthorize("hasAuthority('tb:purchase:order:edit')")
//	public Result save(@RequestBody TbPurchaseOrder data){
//    	try {
//    		service.save(data);
//        	return new Result<>(Result.CODE_SUCCESS,"保存成功");
//		} catch (Exception e) {
//			log.error("保存失败:{}",e);
//        	return new Result<>(Result.CODE_FAILED,"保存失败");
//		}
//
//	}


	@ApiOperation(value = "采购订单-主表删除", notes = "通过id删除采购订单-主表信息。")
	@RequestMapping(value = "/delete", method = RequestMethod.GET)
    //@PreAuthorize("hasAuthority('tb:purchase:order:delete')")
	public Message delete(@RequestParam(value="id") String id) {
		try {
			service.removeById(id);
			return Message.success("删除成功");
		} catch (Exception e) {
			log.error("删除失败:{}",e);
			return Message.error(1,"删除失败");
		}

	}

	/**
	 * 通过采购订单id 获取采购订单详细信息
	 * @author 苏小林
	 * @date 2020/6/10 15:48
	 * @param: id
	 * @return: com.xhsj.user.sms.utils.Message
	 */
	@ApiOperation(value = "通过采购订单id 获取采购订单详细信息", notes = "通过采购订单id 获取采购订单详细信息。")
	@RequestMapping(value = "/getPurchaseOrderInfoById", method = RequestMethod.GET)
	public Message getPurchaseOrderInfoById(@RequestParam("id") String id) {
		try {
			TbPurchaseOrder tbPurchaseOrder = service.getPurchaseOrderInfoById(id);
			return Message.success("成功",tbPurchaseOrder);
		} catch (Exception e) {
			log.error("删除失败:{}",e);
			return Message.error(1,"删除失败");
		}
	}

	@ApiOperation(value = "批量删除", notes = "批量删除。")
	@RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
	public Message batchDelete(@RequestBody List<String> list) {
		try {
			service.removeByIds(list);
			return Message.success("删除成功");
		} catch (Exception e) {
    		log.error("删除失败:{}",e);
			return Message.error(1,"删除失败");
		}
    }

	@ApiOperation(value = "分页查询采购订单-主表list", notes = "带参数查询,{\"page\": 1,\"size\": 5,......}。支持模糊查询")
	@RequestMapping(value="/findList",method = RequestMethod.POST)
    //@PreAuthorize("hasAuthority('tb:purchase:order:view')")
	public Message findList(@RequestBody Map<String,Object> data) {
        try {
        	IPage<TbPurchaseOrder> page = service.selectPage(data);
			return Message.success("成功",page.getRecords(),page.getTotal(),page.getPages());
        } catch (Exception e) {
			log.error("查询异常:{}",e);
			return Message.error(1,"失败");
        }
	}



	@ApiOperation(value = "通过id获取采购订单任务子任务-采购订单任务子任务修改", notes = "通过id获取采购订单任务子任务-采购订单任务子任务修改")
	@RequestMapping(value="/getPurchaseOrderById",method = RequestMethod.GET)
    //@PreAuthorize("hasAuthority('tb:purchase:order:view')")
	public Message getPurchaseOrderById(@RequestParam(value="id") String id) {

		TbPurchaseOrderSubtask tbPurchaseOrder = tbPurchaseApplyService.getPurchaseOrderSubtaskById(id);
		String div = StringUtils.div(tbPurchaseOrder.getSecondProportion(), 100, 2);
		String mul = StringUtils.mul(tbPurchaseOrder.getTotalMoney(), div,2);
		tbPurchaseOrder.setSecondAmount(mul);

        //获取支付记录
		String advanceMoney="0";
		String secondMoney="0";
		List<Map<String,Object>> paymentRecordList = tbPurchaseOrderPaymentRecordMapper.getPaymentRecord(id);
		for (Map<String,Object> paymentRecord : paymentRecordList
			 ) {
			if("1".equals(String.valueOf(paymentRecord.get("batch")))){
				  advanceMoney=String.valueOf(paymentRecord.get("paymentMoney"));
			}else if("2".equals(String.valueOf(paymentRecord.get("batch")))){
				  secondMoney=String.valueOf(paymentRecord.get("paymentMoney"));
			}
		}
		String addMoney = StringUtils.add(advanceMoney, secondMoney);
		String mul1 = StringUtils.sub(tbPurchaseOrder.getTotalMoney(), addMoney);
//		String div1 = StringUtils.div(tbPurchaseOrder.getFinalProportion(), 100, 2);
//		String mul1 = StringUtils.mul(tbPurchaseOrder.getTotalMoney(), div1);
		//尾款金额
		tbPurchaseOrder.setFinalAmount(mul1);
        // 计算总价格
        String total = "";
        List<TbPurchaseSubtaskList> purchaseOrderGoodsList = tbPurchaseOrder.getPurchaseOrderGoodsList();
        if (!purchaseOrderGoodsList.isEmpty()) {
            for (TbPurchaseSubtaskList tbPurchaseOrderGoods : purchaseOrderGoodsList) {
                total = StringUtils.add(total, StringUtils.mul(tbPurchaseOrderGoods.getPrice(), tbPurchaseOrderGoods.getApplyNumber(),2));
            }
        }
        return Message.success("成功",tbPurchaseOrder);

    }


    /**
     * 查询采购订单相关文件
     * @author 苏小林
     * @date 2020/5/27 16:36
     * @param: id
     */
	@ApiOperation(value = "查询采购订单相关文件", notes = "查询采购订单相关文件")
	@RequestMapping(value="/getPurchaseOrderFileByOrderId",method = RequestMethod.GET)
    public Message getPurchaseOrderFileByOrderId(@RequestParam(value="id") String id){

		try {
			List<TbPurchaseOrderFile> list = tbPurchaseOrderFileService.getPurchaseOrderFileByOrderId(id);
			return Message.success("成功",list);
		} catch (Exception e) {
			log.error("查询失败:{}",e);
			return Message.error();
		}
	}


	/**
	 * 查询完整合同文件和付款金额
	 * @author 苏小林
	 * @date 2020/6/1 14:23
	 * @param: id
	 * @return: com.xhsj.user.sms.utils.Message
	 */
	@ApiOperation(value = "查询完整合同文件和付款金额", notes = "查询完整合同文件和付款金额")
	@RequestMapping(value="/getContractFileAndPaymentAmount",method = RequestMethod.GET)
	public Message getContractFileAndPaymentAmount(@RequestParam(value="id") String id) {
		try {
			QueryWrapper<TbPurchaseSubtaskOtherFile> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("type",3);
			queryWrapper.eq("data_id",id);
			List<TbPurchaseSubtaskOtherFile> list = tbPurchaseSubtaskOtherFileService.list(queryWrapper);
			Map<String,Object> money = tbPurchaseSubtaskPaymentApplyMapper.getMoneyByBatch(1,id);
			Map<String, Object> map = Maps.newHashMap();
			map.put("paymentMoney",money.get("paymentMoney"));
			map.put("paymentId",money.get("id"));
			map.put("tbPurchaseOrderFileList",list);
			return Message.success("成功",map);
		} catch (Exception e) {
			log.error("查询失败:{}",e);
			return Message.error();
		}
	}

	/**
	 * 获取结算信息
	 * @author 苏小林
	 * @date 2020/6/5 13:06
	 * @return: com.xhsj.user.sms.utils.Message
	 */
	@ApiOperation(value = "获取结算信息", notes = "获取结算信息")
	@RequestMapping(value="/getSettlementInfo",method = RequestMethod.GET)
	public Message getSettlementInfo(@RequestParam("purchaseOrderId") String purchaseOrderId) {
        try {
		Map<String, Object> map = Maps.newHashMap();

        TbPurchaseOrderSubtask tbPurchaseOrder = tbPurchaseOrderSubtaskService.getPurchaseOrderSubtaskById(purchaseOrderId);

		// 获取入库信息
		List<Map<String,Object>> list = tbPurchaseOrderGoodsMapper.getInStorageByOrderId(purchaseOrderId);
		// 入库应付金额
		String payMentMoney = "0";
		for (Map<String, Object> stringObjectMap : list) {
			payMentMoney = StringUtils.add(payMentMoney, stringObjectMap.get("paymentMoney"));
		}

		// 获取支付信息
		List<Map<String,Object>> list1 = tbPurchaseOrderPaymentRecordMapper.getPaymentRecord(purchaseOrderId);
		String payment = "0";
		for (Map<String, Object> objectMap : list1) {
			Object paymentMoney = objectMap.get("paymentMoney");
			payment = StringUtils.add(payment, paymentMoney);
		}

		map.put("inStorageInfo",list);
		map.put("paymentInfo",list1);
		map.put("totalMoney",tbPurchaseOrder.getTotalMoney());// 总金额
		map.put("payment",payment);// 已经支付金额

		BigDecimal bigDecimal = new BigDecimal(payMentMoney);
		BigDecimal bigDecimal1 = new BigDecimal(payment);
		int i = bigDecimal.compareTo(bigDecimal1);
        BigDecimal receive=new BigDecimal(0);
        BigDecimal pay=new BigDecimal(0);
		if (i == -1) {// 小于
            receive=bigDecimal1.subtract(bigDecimal);
		}else if (i==1) {// 大于
            pay=bigDecimal.subtract(bigDecimal1);
		}
        map.put("receive",receive);
        map.put("pay",pay);
		return Message.success("",map);
        } catch (Exception e) {
            log.error("查询失败:{}",e);
            return Message.error();
        }
	}


    @ApiOperation(value = "从结算表中获取结算信息", notes = "从结算表中获取结算信息")
    @RequestMapping(value="/getSettlementInfoByDB",method = RequestMethod.GET)
    public Message getSettlementInfoByDB(@RequestParam("purchaseOrderSubtaskId") String purchaseOrderSubtaskId) {
        try {
            Map<String, Object> map = Maps.newHashMap();
            QueryWrapper queryWrapper=new QueryWrapper();
            queryWrapper.eq("data_id",purchaseOrderSubtaskId);
            TbPurchaseSubtaskStatement subtaskStatement = tbPurchaseSubtaskStatementService.getOne(queryWrapper);

            // 获取入库信息
            List<Map<String,Object>> list = tbPurchaseOrderGoodsMapper.getInStorageByOrderId(purchaseOrderSubtaskId);
            // 入库应付金额
            String payMentMoney = "0";
            for (Map<String, Object> stringObjectMap : list) {
                payMentMoney = StringUtils.add(payMentMoney, stringObjectMap.get("paymentMoney"));
            }

            // 获取支付信息
            List<Map<String,Object>> list1 = tbPurchaseOrderPaymentRecordMapper.getPaymentRecord(purchaseOrderSubtaskId);
            String payment = "0";
            for (Map<String, Object> objectMap : list1) {
                Object paymentMoney = objectMap.get("paymentMoney");
                payment = StringUtils.add(payment, paymentMoney);
            }
            map.put("inStorageInfo",list);
            map.put("paymentInfo",list1);
            map.put("totalMoney",subtaskStatement.getContractTotalMoney());// 总金额
            map.put("payment",payment);// 已经支付金额
            map.put("paymentMoney",subtaskStatement.getPaymentMoney());//需要付款的金额
            map.put("type",subtaskStatement.getType()); //1应收 2应付
            return Message.success("",map);
        } catch (Exception e) {
            log.error("查询失败:{}",e);
            return Message.error();
        }
    }

	@ApiOperation(value = "查询任务下面的订单列表", notes = "查询任务下面的订单列表")
	@RequestMapping(value="/getPurchaseOrderListByTaskId",method = RequestMethod.GET)
	public Message getPurchaseOrderListByTaskId(@RequestParam("taskId") String taskId) {

		try {
			List<TbPurchaseOrder> list = service.getPurchaseOrderListByTaskId(taskId);
			return Message.success("",list);
		} catch (Exception e) {
			log.error("查询失败:{}",e);
			return Message.error();
		}
	}

	/**
	 *
	 * @author 苏小林
	 * @date 2020/6/12 10:04
	 * @param: orderId
	 * @return: com.xhsj.user.sms.utils.Message
	 *
	 */
	@ApiOperation(value = "获取订单商品列表", notes = "获取订单商品列表")
	@RequestMapping(value="/getOrderGoodsList",method = RequestMethod.GET)
	public Message getOrderGoodsList(@RequestParam("orderId") String orderId) {

		try {
			List<TbPurchaseOrderGoods> list = service.getOrderGoodsList(orderId);
			return Message.success("",list);
		} catch (Exception e) {
			log.error("查询失败:{}",e);
			return Message.error();
		}

	}


	public static void main(String[] args) {
		for (int i = 0; i < 10; i++) {
			System.err.println(IdGen.uuid());

		}
	}
}

